﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DBConnections.aspx.cs" Inherits="ReportsFactory.DBConnections" EnableEventValidation="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
	<title>Reports Factory</title>
	<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
	<script src="Scripts/jquery-ui-1.8.11.custom.min.js" type="text/javascript"></script>
	<script src="Scripts/jquery.ui.core.js" type="text/javascript"></script>
	<script src="Scripts/jquery.ui.widget.js" type="text/javascript"></script>
	<script src="Scripts/jquery.ui.mouse.js" type="text/javascript"></script>
	<script src="Scripts/jquery.ui.draggable.js" type="text/javascript"></script>
	<script src="Scripts/jquery.ui.droppable.js" type="text/javascript"></script>
	<script src="Scripts/wz_jsgraphics.js" type="text/javascript"></script>
	<script src="Scripts/jquery.selectboxes.js" type="text/javascript"></script>
	<script src="Scripts/jquery.conmenu.js" type="text/javascript"></script>
	<link href="Styles/Site.css" rel="stylesheet" type="text/css" />

	<style type="text/css">
		.panel
		{
			cursor: move;	
		}
		
		.style1
		{
			width: 134px;
		}
		.style2
		{
			width: 183px;
		}
		.style3
		{
			width: 507px;
		}
	</style>

	<script type="text/javascript" language="javascript">
		var jg = null;

		function CheckReportSelected()
		{
			var checked = false;
			$('#rdlstMyReports input').each(function ()
			{
				checked = true;
			});

			$('#rdlstPublicReports input').each(function ()
			{
				checked = true;
			});

			if (!checked)
			{
				alert('No report selected');
				return false;
			}
			else
				return true;
		}

		function CheckConnectionExist() {
			var checked = false;
			$('#chkLstConnections input').each(function () {
				checked = true;
			});

			if (!checked) {
				alert('No database connection found in the list');
				return false;
			}
			else
				return true;
		}

		function CheckTableSelected()
		{
			var checked = false;
			$('#chkLstSelectedTables input').each(function ()
			{
				checked = true;
			});

			if (!checked)
			{
				alert('No tables selected!');
				return false;
			}
			else
				return true;
		}

		//Presist all data in listbox to a  hiddent field to be read by server
		function PersistRelation() {
			$("#hdnRelationData").val('');
			$('#lstRelations > option').each(function (index) {
				var existingVal = $("#hdnRelationData").val();
				$("#hdnRelationData").val(existingVal + "||" + $(this).text());
			});

			$("#hdnTables").val('');
			$('.draggableItem').each(function () {
				var existingVal = $("#hdnTables").val();
				$("#hdnTables").val(existingVal + "||" + $(this).context.id);
			});

			$("#hdnTableData").val('');
			$('.draggableItem input:checked').each(function () {
				var existingVal = $("#hdnTableData").val();
				var id = $(this).context.id.substring(0, $(this).context.id.lastIndexOf('_'));
				$("#hdnTableData").val(existingVal + "||" + id + "^" + $(this).context.value);
			});
			return true;
		}

		function ShowRelations(div)
		{
			var divId = ($(div).attr("id"));
			var colNames = new Array();
			var srcCon = null;
			var tgtCon = null;
			//Build all relations for the selcted table
			if (divId.indexOf("---") > 0)
			{
				$('#lstRelations > option').each(function (index)
				{
					if ($(this).text().indexOf(divId) > -1)
					{
						var spl = $(this).text().split("^");
						if (spl[0] == divId)
						{
							var colName = {};

							var srcTbl = spl[0].split("---");
							colName.srcTab = srcTbl[0];
							colName.srcCol = spl[1];
							srcCon = srcTbl[1];

							var tgtTbl = spl[2].split("---");
							colName.tgtTab = tgtTbl[0];
							colName.tgtCol = spl[3];
							tgtCon = tgtTbl[1];

							colNames.push(colName);
						}
						else if (spl[2] == divId)
						{
							var colName = {};

							var tgtTbl = spl[0].split("---");
							colName.tgtTab = tgtTbl[0];
							colName.tgtCol = spl[1];
							tgtCon = tgtTbl[1];

							var srcTbl = spl[2].split("---");
							colName.srcTab = srcTbl[0];
							colName.srcCol = spl[3];
							srcCon = srcTbl[1];

							colNames.push(colName);
						}
					}
				});
			}

			if (colNames.length > 0)
			{
				//pass relation array to popup window
				var vw = window.showModalDialog("RemoveTableRelation.aspx", colNames, "dialogWidth:800px; dialogHeight:500px");

				if (vw == null)
					return;

				//Get all indexes to remove
				var idxToRemove = new Array();
				$('#lstRelations > option').each(function (index)
				{
					if ($(this).text().indexOf(divId) > -1)
						idxToRemove.push(index);
				});

				//Reverse indexes and remove from listbox
				idxToRemove = idxToRemove.reverse();
				for (var x = 0; x < idxToRemove.length; x++)
					$("#lstRelations").removeOption(idxToRemove[x]);

				//Add items based on data passed from popup window
				for (var x = 0; x < vw.length; x++)
				{
					var itemToAdd = vw[x].srcTab + "---" + srcCon + "^" + vw[x].srcCol + "^" + vw[x].tgtTab + "---" + tgtCon + "^" + vw[x].tgtCol;
					$("#lstRelations").addOption(itemToAdd, itemToAdd, false);
				}

				ReDrawLines();

			}
			else
				alert('No relations found!');
		}

		$(function ()
		{
		    //Show context menu on the DIV clicked
		    $.conmenu({
		        selector: ".draggable",
		        choices: [{
		            label: "View Relationships",
		            action: function (div)
		            {
		                ShowRelations(div);
		            }
		        }]
		    });

		    //Create new JS Graphics element
		    if (document.getElementById("columnsDiv") && jg == null)
		        jg = new jsGraphics("columnsDiv");

		    //When an element is dragged re-create lines
		    $(".draggable").draggable({ containment: ".colsDiv",
		        stop: function ()
		        {
		            ReDrawLines();
		        }
		    });

		    //Creates a draggbale item UI 
		    $(".draggableItem label").draggable({
		        cursor: "vertical-text",
		        appendTo: "body",
		        helper: "clone"
		    });

		    //When an element is dropped create relationships & draw lines
		    $(".droppable").droppable({
		        drop: function (event, ui)
		        {
		            var sourceTbl = ui.draggable[0].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.id;

		            if (sourceTbl != "colsDiv" && sourceTbl != null && sourceTbl != "columnsDiv")
		            {
		                var targetTable = this.id;
		                var fieldName = ui.helper.context.innerHTML;

		                if (targetTable != "" && fieldName != "" && (targetTable != sourceTbl))
		                {
		                    var colNames = {};
		                    colNames.srcCol = "";
		                    colNames.tgtCol = "";

		                    var vw = window.showModalDialog("TableRelation.aspx?SrcTable=" + sourceTbl + "&TgtTable=" + targetTable + "&FldName=" + fieldName, colNames, "dialogWidth:600px; dialogHeight:200px");
		                    if (vw == null)
		                        return;

		                    if (colNames != null && colNames.srcCol != null && vw.tgtCol != null)
		                    {
		                        var itemToAdd = sourceTbl + "^" + vw.srcCol + "^" + targetTable + "^" + vw.tgtCol;
		                        $("#lstRelations").addOption(itemToAdd, itemToAdd, false);
		                        DrawLine(sourceTbl, targetTable);
		                    }

		                    return false;
		                }
		            }
		        }
		    });

		    $('#filterTable input[type=checkbox]').live('click', function ()
		    {
		        var row = $(this).parents("tr:first");
		        $(row).remove();
		        if ($(this).attr('checked'))
		        {
		            $('#filterTable').prepend(row);
		            $('#filterTable .filterColTb:first').focus();
		        }
		        else
		            $('#filterTable').append(row);
		    });

		    $('#filterTable .filterColTb').live('blur', function ()
		    {
		        var row = $(this).parents("tr");
		        var cb = row.find('td input[type=checkbox]')

		        if ($(this).val() == null || $(this).val() == "")
		        {
		            if ($(cb).attr('checked'))
		            {
		                $(cb).removeAttr('checked');
		                $(row).remove();
		                $('#filterTable').append(row);
		            }
		        }
		        else
		        {
		            if (!$(cb).attr('checked'))
		            {
		                $(cb).attr('checked', 'checked');
		                $(row).remove();
		                $('#filterTable').prepend(row);
		            }
		        }

		    });

		});

		function ReDrawLines()
		{
			//Hide right click menu
			$(".contextmenu").hide();
			ClearLines();

			//Draw lines bases on the item in the listbox
			$('#lstRelations > option').each(function (index)
			{
				var spl = $(this).text().split("^");
				DrawLine(spl[0], spl[2]);
			});
		}
	
		//Draws a line based on 2 elements
		function DrawLine(srcElement, tgtElement) {
			if (!document.getElementById("columnsDiv"))
			{
				alert('Cannot draw line. Canvas not found');
				return;
			}

			if (jg == null)
				jg = new jsGraphics("columnsDiv");

			jg.setColor("#000000");

			var src = document.getElementById(srcElement);
			var srcChild = document.getElementById(srcElement.replace('---', '----'));
			var tgt = document.getElementById(tgtElement);
			var tgtChild = document.getElementById(tgtElement.replace('---', '----'));
			var srcHt = srcChild.offsetHeight >= 200 ? 200 : srcChild.offsetHeight;
			var tgtHt = tgtChild.offsetHeight >= 200 ? 200 : tgtChild.offsetHeight;

			var srcPos = "Left";
			if (src.offsetTop + srcHt + 50 < tgt.offsetTop)
				srcPos = "Top"
			else if (tgt.offsetTop + tgtHt + 50 < src.offsetTop)
				srcPos = "Bottom"
			else if (src.offsetLeft + src.offsetWidth  > tgt.offsetLeft)
				srcPos = "Right"

			if (srcPos == "Left")
				jg.drawLine(src.offsetLeft + src.offsetWidth, src.offsetTop + (srcHt / 2), tgt.offsetLeft, tgt.offsetTop + (tgtHt / 2));
			else if (srcPos == "Right")
				jg.drawLine(src.offsetLeft, src.offsetTop + (srcHt / 2), tgt.offsetLeft + tgt.offsetWidth, tgt.offsetTop + (tgtHt / 2));
			else if (srcPos == "Top")
				jg.drawLine(src.offsetLeft + (src.offsetWidth / 2), src.offsetTop + srcHt + 25, tgt.offsetLeft + (tgt.offsetWidth / 2), tgt.offsetTop);
			else if (srcPos == "Bottom")
				jg.drawLine(tgt.offsetLeft + (tgt.offsetWidth / 2), tgt.offsetTop + tgtHt + 25, src.offsetLeft + (src.offsetWidth / 2), src.offsetTop);

			jg.paint();
		}

		//Clear the lines
		function ClearLines() {
			if (jg != null)
				jg.clear();

		}

		function UnCheck(otherClass)
		{
			$('.' + otherClass + ' input').attr('checked', false);
		}

    </script>

	</head>
<body id="body">
	<form id="form1" runat="server">
	
	<div id="startDiv" runat="server">
		<table>
			<tr>
				<td colspan="3">
					<h2>
						Welcome to Reports Factory. What do you like to do?
					</h2>
				</td>
			</tr>
			<tr>
				<td>
					<asp:Button Text="Create a new report" CssClass="btn" ID="cmdCreateReport" runat="server" onclick="cmdCreateReport_Click" />
				</td>
				<td>
					<asp:Button Text="Edit a report" CssClass="btn" ID="cmdEditReport" runat="server" onclick="cmdEditReport_Click" />
				</td>
				<td>
					<asp:Button Text="Run a saved report" CssClass="btn" ID="cmdRunReport" runat="server" onclick="cmdRunReport_Click" />
				</td>
			</tr>
		</table>
	</div>

	<div id="reportsDiv" runat="server" visible="false">
		<table>
			<tr>
				<td valign="top">
					<asp:Panel GroupingText="My Reports" ID="panelMyRpt" runat="server">
						<asp:RadioButtonList runat="server" ID="rdlstMyReports" CssClass="myReports" onclick="javascript:UnCheck('publicReports');" />
					</asp:Panel>
				</td>
				<td>
					&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
				</td>
				<td valign="top">
					<asp:Panel GroupingText="Public Reports" ID="panelPublicRpt" runat="server">
						<asp:RadioButtonList runat="server" ID="rdlstPublicReports" CssClass="publicReports" onclick="javascript:UnCheck('myReports');" />
					</asp:Panel>
				</td>
			</tr>
		</table>
	
		<div class="alwaysVisible bottomRight">
			<asp:Button Text="Previous" CssClass="btn" runat="server" ID="cmdReportsPrevious" OnClick="cmdReportsPrevious_Click" />
			&nbsp;
			<asp:Button CssClass="btn" Text="Next" ID="cmdReportsNext" runat="server" OnClientClick="javascript:return CheckReportSelected();" OnClick="cmdReportsNext_Click" />
		</div>
	</div>

	<div id="dbDiv" runat="server" visible="false">
		<table width="100%">
			<tr>
				<td class="style1">
					Database Type
				</td>
				<td class="style2">
					<asp:DropDownList ID="ddlDatabaseType" runat="server">
						<asp:ListItem Selected="True" Text="SQL Server" Value="SQL Server" />
					</asp:DropDownList>
				</td>
				<td class="style2" rowspan="6" align="center">
					<asp:Button CssClass="btn" Text="Test Connection" runat="server" ID="cmdTestCon"  onclick="cmdTestCon_Click" />
					<br />
					<br />
					<asp:Button CssClass="btn" Text="Add Connection" runat="server" ID="cmdAddCon"  onclick="cmdAddCon_Click"  />
				</td>
				<td rowspan="11" style="text-align:left;vertical-align:top">
					<asp:Button CssClass="btn" Text="Remove Selected" runat="server" ID="cmdRemoveCon"   onclick="cmdRemoveCon_Click"  />
					<br />
					<asp:CheckBoxList ID="chkLstConnections" runat="server" />
					<br />
				</td>
			</tr>
			<tr>
				<td class="style1">
					Server Name/IP
				</td>
				<td class="style2">
					<asp:TextBox ID="txtServerName" runat="server" Width="120px" Text="localhost" />
				</td>
			</tr>
			<tr>
				<td class="style1">
					Database Name
				</td>
				<td class="style2">
					<asp:TextBox ID="txtDBName" runat="server" Width="120px" Text="test" />
				</td>
			</tr>
			<tr>
				<td class="style1">
					Authentication Type
				</td>
				<td class="style2">
					<asp:DropDownList ID="ddlAuthentication" runat="server" AutoPostBack="true"  
						onselectedindexchanged="ddlAuthentication_SelectedIndexChanged">
						<asp:ListItem Selected="True" Text="Windows Authentication" Value="Windows Authentication" />
						<asp:ListItem Text="User Name & Password" Value="User Name & Password" />
					</asp:DropDownList>
				</td>
			</tr>
			<tr>
				<td class="style1">
					User Name
				</td>
				<td class="style2">
					<asp:TextBox ID="txtUserName" runat="server" Enabled="false" Width="120px" />
				</td>
			</tr>
			<tr>
				<td class="style1">
					Password
				</td>
				<td class="style2">
					<asp:TextBox ID="txtPassword" runat="server" TextMode="Password" Enabled="false" Width="120px" />
				</td>
			</tr>
		</table>
	
		<span runat="server" ID="spnMsg"></span>

		<div class="alwaysVisible bottomRight">
			<asp:Button Text="Previous" CssClass="btn" ID="cmdDBPrevious" runat="server" onclick="cmdDBPrevious_Click" />
			&nbsp;
			<asp:Button CssClass="btn" Text="Next" runat="server" ID="cmdDBNext" 
				OnClientClick ="javascript:return CheckConnectionExist();" OnClick="cmdDBNext_Click" />
		</div>
	</div>

	<div id="tablesDiv" runat="server" visible="false">
		<table width="100%">
			<tr>
				<td class="style3">
					Select DB:&nbsp;&nbsp;
					<asp:DropDownList ID="ddlConnectionStrings" runat="server" AutoPostBack="true" 
						onselectedindexchanged="ddlConnectionStrings_SelectedIndexChanged" />
				</td>
			</tr>
			<tr>
				<td>
					<div style="height: 500px; overflow: scroll; width: 500px">
						<br />
						<asp:CheckBoxList ID="chkLstTables" runat="server" />
					</div>
				</td>
				<td>
					<asp:Button CssClass="btn" ID="cmdAddTables" runat="server" Text="Add >"  
						onclick="cmdAddTables_Click" Width="70px" />
					<br />
					<br />
					<asp:Button CssClass="btn" ID="cmdRemoveTables" runat="server" Text="< Remove" 
						onclick="cmdRemoveTables_Click" Width="70px" />
				</td>
				<td>
					<div style="height: 500px; overflow: scroll; width: 500px">
						<br />
						<asp:CheckBoxList ID="chkLstSelectedTables" runat="server" />
					</div>
				</td>
			</tr>
		   
		</table>

		<div class="alwaysVisible bottomRight">
			<asp:Button Text="Previous" CssClass="btn" ID="cmdTablesPrevious" runat="server" onclick="cmdTablesPrevious_Click" />
			&nbsp;
			<asp:Button Text="Next" CssClass="btn" ID="cmdTablesNext" runat="server" 
				OnClientClick="javascript:return CheckTableSelected();" OnClick="cmdTablesNext_Click" />
		</div>
	</div>

	<div id="columnsDiv" runat="server" visible="false">
		<table width="100%">
			<tr>
				<td>
					<div id="colsDiv" class="colsDiv" runat="server" style="border: solid 1px black; height: 800px; width: 1250px; overflow: none;">
					</div>
				</td>
			</tr>
		</table>


		<asp:ListBox ID="lstRelations" runat="server" Width="100%" />
		
		<br />
		<asp:HiddenField ID="hdnRelationData" runat="server" />
		<asp:HiddenField ID="hdnTableData" runat="server" />
		<asp:HiddenField ID="hdnTables" runat="server" />

		<div class="alwaysVisible bottomRight">
			<asp:Button Text="Previous" CssClass="btn" ID="cmdColsPrevious" runat="server" OnClick="cmdColsPrevious_Click" />
			&nbsp;
			<asp:Button Text="Next" CssClass="btn" ID="cmdColsNext" runat="server" OnClientClick="javascript:return PersistRelation()" OnClick="cmdColsNext_Click" />
		</div>
	</div>

	<div id="filterDiv" runat="server" visible="false">
		<table id="filterTable" runat="server">

		</table>
		<div class="alwaysVisible bottomRight">
			<asp:Button Text="Previous" CssClass="btn" ID="cmdFilterPrevious" runat="server" OnClick="cmdFilterPrevious_Click" />
			&nbsp;
			<asp:Button Text="Next" CssClass="btn" ID="cmdFilterNext" runat="server" OnClick="cmdFilterNext_Click" />
		</div>
	</div>

	<div id="saveRptDiv" runat="server" visible="false">
		<table>
			 <tr id="trSaveReport" runat="server">
				<td>
					Save this report:
				</td>
				<td>
					<asp:CheckBox runat="server" ID="chkboxSaveReport" AutoPostBack="true" 
						Checked="true" oncheckedchanged="chkboxSaveReport_CheckedChanged" />
				</td>
			</tr>

			<tr id="trReportName" runat="server">
				<td>
					Enter a name for this report:
				</td>
				<td>
					<asp:TextBox runat="server" ID="txtReportName" />
				</td>
			</tr>

			<tr id="trMakePublic" runat="server">
				<td>
					Make this report public:
				</td>
				<td>
					<asp:CheckBox runat="server" ID="chkboxMakePublic" />
				</td>
			</tr>
		</table>


		<div class="alwaysVisible bottomRight">
			<asp:Button Text="Previous" CssClass="btn" ID="cmdPreviewPrevious" runat="server" OnClick="cmdPreviewPrevious_Click" />
			&nbsp;
			<asp:Button Text="Next" CssClass="btn" ID="cmdPreviewNext" OnClick="cmdPreviewNext_Click" runat="server" />
		</div>
	</div>
	
	</form>
</body>


</html>
